from datetime import datetime
from lg_config import FLIGHT_STATS_PASSWORD
from lg_flight_db import DepartureFlightInfo
from xml.dom import minidom
from xml.etree import ElementTree
import logging
import urllib2

FLIGHT_STATS_URL = "https://www.pathfinder-xml.com/development/xml?"
FLIGHT_STATS_CRE = "&login.accountID=8527&login.userID=lazygalaxy&login.password=" + FLIGHT_STATS_PASSWORD + "&"


STATIC_AIRPORT_INFO = "http://folder.lazygalaxy.com/home/airport_info.xml"
AIRPORT_INFO_KEY_FIELD = 'AirportCode'
def get_airport_info_api():
    #url = FLIGHT_STATS_URL + "Service=AirportGetAirportsService" + FLIGHT_STATS_CRE + "airportGetAirportsInfo.airportGetAirportsRequestedData.airportDetails=true"
    url = STATIC_AIRPORT_INFO
    root = ElementTree.parse(urllib2.urlopen(url)).getroot()
    
    airport_info_dict = {}
    for airport_detail in root:
        if airport_detail.tag == '{http://pathfinder-xml/AirportService.xsd}AirportDetail':
            if not AIRPORT_INFO_KEY_FIELD in airport_detail.attrib:
                raise Exception(AIRPORT_INFO_KEY_FIELD + " not found for " + str(airport_detail.attrib)) 
            key = airport_detail.attrib[AIRPORT_INFO_KEY_FIELD]
            if key in airport_info_dict:
                logging.error(key + " already exists in dict") 
            else:
                airport_info_dict[key] = airport_detail.attrib
                
    return airport_info_dict

STATIC_AIRLINE_INFO = "http://folder.lazygalaxy.com/home/airline_info.xml"
AIRLINE_INFO_KEY_FIELD = 'AirlineCode'
def get_airline_info_api():
    #url = FLIGHT_STATS_URL + "Service=AirlineGetAirlinesService" + FLIGHT_STATS_CRE + "&&airlineGetAirlinesInfo.airlineGetAirlinesRequestedData.airlineDetails=true"
    url = STATIC_AIRLINE_INFO
    root = ElementTree.parse(urllib2.urlopen(url)).getroot()
    
    airline_info_dict = {}
    for airline_detail in root:
        for child in airline_detail:
            if child.tag == '{http://pathfinder-xml/AirlineService.xsd}Airline':
                
                if not AIRLINE_INFO_KEY_FIELD in child.attrib:
                    raise Exception(AIRLINE_INFO_KEY_FIELD + " not found for " + str(child.attrib)) 
                key = child.attrib[AIRLINE_INFO_KEY_FIELD]
                if key in airline_info_dict:
                    logging.error(key + " already exists in dict") 
                else:
                    airline_info_dict[key] = child.attrib
                
    return airline_info_dict


def get_departure_flight_info_api(airport, date):
    url = FLIGHT_STATS_URL + "Service=FlightHistoryGetRecordsService" + FLIGHT_STATS_CRE + "info.specificationDepartures[0].airport.airportCode=" + airport + "&info.specificationDateRange.departureDateTimeMin=" + date + "T00:00:00.000&info.specificationDateRange.departureDateTimeMax=" + date + "T23:59:59.999"
    content = urllib2.urlopen(url).read()

    dom = minidom.parseString(content)
    departures = []
    for node in dom.getElementsByTagName('FlightHistory'):
        airline = node.childNodes[0]
        origin = node.childNodes[1]
        destination = node.childNodes[2]
        
        airline_iata_code = airline.getAttribute('IATACode')
     
        origin_airport_iata_code = origin.getAttribute('IATACode')
      
        destination_airport_iata_code = destination.getAttribute('IATACode')
       
        departure_date_str = node.getAttribute('DepartureDate');
        departure_date = datetime.strptime(departure_date_str, '%Y-%m-%dT%H:%M:%S.000') 
        departure_timezone_offset = int(node.getAttribute('DepartureAirportTimeZoneOffset'))
        arrival_date = datetime.strptime(node.getAttribute('ArrivalDate'), '%Y-%m-%dT%H:%M:%S.000') 
        arrival_timezone_offset = int(node.getAttribute('ArrivalAirportTimeZoneOffset'))
        flight_number = node.getAttribute('FlightNumber')
        aircraft_type = node.getAttribute('ScheduledAircraftType')
        
        flight_info = DepartureFlightInfo(key_name=departure_date_str + '_' + origin_airport_iata_code + '_' + airline_iata_code + flight_number, departure_date=departure_date, departure_airport_iata_code=origin_airport_iata_code, departure_timezone_offset=departure_timezone_offset, arrival_date=arrival_date, arrival_airport_iata_code=destination_airport_iata_code, arrival_timezone_offset=arrival_timezone_offset, airline_code=airline_iata_code, flight_number=flight_number, aircraft_type=aircraft_type)
        departures.append(flight_info)
    return departures
